package com.app.mingluxing.net;

import android.app.ProgressDialog;
import android.content.Context;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.app.mingluxing.base.MyApplication;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.LogUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 网络请求工具
 * Created by Aaron on 2015/7/16.
 */
public class HttpUtil {

//    private HttpUtil() {
//
//        httpUtils = new HttpUtils();
//        httpUtils.configCurrentHttpCacheExpiry(0);
//        httpUtils.configDefaultHttpCacheExpiry(0);
//        httpUtils.configSoTimeout(6 * 1000);
//        httpUtils.configTimeout(6 * 1000);
//    }
//
//    private static HttpUtil httpUtil = new HttpUtil();
//
//    public static HttpUtil getInstance() {
//
//        return httpUtil;
//    }
//
//    private HttpUtils httpUtils;

    /**
     * POST 请求
     *
     * @param message 提示信息
     * @param ctx     上下文对象
     * @param url     url地址
     * @param params  提交给服务器的json参数
     * @param success 成功的监听
     * @param fail    失败的监听
     */
    public static void setPostRequest(String message, final Context ctx, String url, final String params, String tag, final SuccessListener success, final FailListener fail) {

        final ProgressDialog show = ProgressDialog.show(ctx, message, Constant.WAIT);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                if (show != null && show.isShowing()) {
                    try {
                        show.dismiss();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                LogUtil.e("TAG", "返回的json===>>>>" + response);

                //成功回调
                if (success != null) {
                    success.setOnSuccessListener(response);
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

                LogUtil.e("tag", "==onErrorResponse==" + error.getMessage()
                        + "\r\n" + error.getLocalizedMessage() + "\r\n" +
                        error.toString() + "\r\n" +
                        error.getLocalizedMessage() + "\r\n" + error.hashCode());

                if (show != null && show.isShowing()) {
                    try {
                        show.dismiss();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                Toast.makeText(ctx, "网络错误!", Toast.LENGTH_SHORT).show();

                if (fail != null) {
                    fail.setOnFailListener();
                }

            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", params);

                LogUtil.e("TAG", "请求的json===>>>>" + params);

                return param;
            }

        };

        //把请求加入队列
        ((MyApplication) ctx.getApplicationContext()).addToRequestQueue(stringRequest, tag);

    }





    /**
     * POST 请求
     *
     * @param ctx     上下文对象
     * @param url     url地址
     * @param params  提交给服务器的json参数
     * @param success 成功的监听
     * @param fail    失败的监听
     */
    public static void setPostNoWaring(final Context ctx, String url, final String params,
                                       String tag, final SuccessListener success, final FailListener fail) {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                LogUtil.e("TAG", "返回的json===:" + response);

                //成功回调
                if (success != null) {
                    success.setOnSuccessListener(response);
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

                if (fail != null) {
                    fail.setOnFailListener();
                }

            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", params);

                LogUtil.e("TAG", "请求的json===>>>>" + params);

                return param;
            }

        };

        //把请求加入队列
        ((MyApplication) ctx.getApplicationContext()).addToRequestQueue(stringRequest, tag);

    }



    public interface SuccessListener {

        void setOnSuccessListener(String str);

    }

    public interface FailListener {

        void setOnFailListener();

    }

    /**
     * 上传图片
     */
    public String load(String URL, byte[] bytes) {

        String text = null;

        try {
            java.net.URL url = new URL(URL);

            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            uc.setRequestProperty(
                    "Accept",
                    "image/gif,   image/x-xbitmap,   image/jpeg,   image/pjpeg,   application/vnd.ms-excel,   " +
                            "application/vnd.ms-powerpoint,   application/msword,   application/x-shockwave-flash,   application/x-quickviewplus,   */*");
            uc.setRequestProperty("Accept-Language", "zh-cn");
            uc.setRequestProperty("Content-type",
                    "multipart/form-data;   boundary=---------------------------7d318fd100112");
            uc.setRequestProperty("Accept-Encoding", "gzip,   deflate");
            uc.setRequestProperty("User-Agent",
                    "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.1)");
            uc.setRequestProperty("Connection", "Keep-Alive");
            uc.setDoOutput(true);
            uc.setRequestMethod("POST");
            //设置容许输出
            uc.setDoOutput(true);
            //不使用缓存
            uc.setUseCaches(false);
            //超时时间10秒
            uc.setConnectTimeout(10000);

            OutputStream out = uc.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();

            int code = uc.getResponseCode();
            String sCurrentLine = "";
            String sTotalString = "";
            if (code == 200) {
                java.io.InputStream is1 = uc.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is1));
                while ((sCurrentLine = reader.readLine()) != null)
                    if (sCurrentLine.length() > 0)
                        sTotalString = sTotalString + sCurrentLine.trim();
            }
            text = sTotalString;
            LogUtil.e("net", text);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text;

    }

}
